import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
import 'EventDispatcher.dart';
import 'BodyWidget.dart';
import 'package:permission_handler/permission_handler.dart';

BodyWidget bw=BodyWidget();


class ClassicBlue{

  late BluetoothConnection connection;

  bool isConnected=false;

  Future<void> getPermission() async{
    await Permission.bluetooth.request();
    await Permission.bluetoothAdvertise.request();
    await Permission.bluetoothConnect.request();
    await Permission.bluetoothScan.request();
  }

  void startScan() async{
    await getPermission();

    FlutterBluetoothSerial.instance.getBondedDevices().then((List<BluetoothDevice> bondedDevices) {
      print("bondedDevices:"+bondedDevices.toString());
      List<Widget> items=[];
      for(BluetoothDevice item in bondedDevices){
        items.add(ListTile(
          title:Text("name:"+item.name.toString()) ,
          onTap: (){
            connectDevice(item);
            Get.back();
            bw.showCallbackInfo("connecting....");
          },
        ));
      }
      Get.defaultDialog(
        title: "Classic Bluetooth list",
        content: Column(children: items,),
      );
    });
  }

  void connectDevice(BluetoothDevice device) async{
    isConnected=false;
    BluetoothConnection.toAddress(device.address).then((BluetoothConnection conn) {
      connection=conn;
      isConnected=true;
      connection.input?.listen((Uint8List data) {
        String msg=utf8.decode(data);
        if(msg!=null && msg.isNotEmpty && msg.trim().length>1){
          bw.showCallbackInfo( utf8.decode(data));
        }
      }).onDone(() {
        isConnected=false;
        bw.showConnectState("${device.name} Disconnected by remote request",0);
      });
      bw.showConnectState("${device.name} connected",1);
    }).onError((error, stackTrace) {
      bw.showConnectState("${device.name} connect error",0);
    });
  }

  void sendData(String data){
    if(connection!=null && isConnected){
      connection.output.add(utf8.encode(data));
    }
  }

  void disconnect(){
    if(connection!=null && isConnected){
      connection.finish(); // Closing connection
      isConnected=false;
    }
  }

}

class MyClassicBlue extends StatelessWidget{

  @override
  Widget build(BuildContext context) {

    RxString theStr="jack".obs;
    RxInt theIndex=0.obs;

    ClassicBlue blue=ClassicBlue();

    EventDispatcher.addEventListener("showDialog_classic",(data){
      blue.startScan();
    });
    EventDispatcher.addEventListener("disconnect_classic",(data){
      blue.disconnect();
    });
    EventDispatcher.addEventListener("sendData_classic",(data){
      blue.sendData(data.toString());
    });

    return Scaffold(
      appBar: AppBar(title:const Text("BLUETOOTH SERIAL"),centerTitle: true,backgroundColor: Colors.cyan, titleTextStyle: const TextStyle(color: Colors.white)),
      body: bw.getWidget(theStr,"classic"),
      bottomNavigationBar: Obx(()=> BottomNavigationBar(items: const [
        BottomNavigationBarItem(icon: Icon(Icons.keyboard_alt_outlined),label: "KEYBOARD"),
        BottomNavigationBarItem(icon: Icon(Icons.compare_arrows),label: "PAN"),
      ],
        onTap: (index){
          if(index==0){
            theStr.value="board";
          }else{
            theStr.value="pan";
          }
          theIndex.value=index;
        },
        currentIndex: theIndex.value,
      )),
    );
  }
}